package com.kefu.chat.smart.condition;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Maps;
import com.kefu.chat.smart.ChatConnectCondition;
import com.kefu.chat.vo.ChatUserParam.UserConnectP;
import com.kefu.chat.vo.ChatUserParam.UserConnectR;
import com.kefu.common.trigger.Condition;
import com.kefu.common.trigger.TriggerWrapper;
import com.kefu.common.trigger.model.ConditionModel;
import com.kefu.common.trigger.model.DynamicModel;
import com.kefu.common.trigger.model.DynamicModel.OptionType;
import com.kefu.common.trigger.model.DynamicModel.SearchType;
import com.kefu.common.util.JacksonUtil;
import com.kefu.crm.model.CrmCustomer;

@Component
public class ChatCustomerFieldsCondition implements ChatConnectCondition<Integer> {

	@Override
	public String getCode() {
		return "customer_fields";
	}

	@Override
	public ConditionModel getConditionModel() {
		Map<String,String> groupSearch=Maps.newHashMap();
		 groupSearch.put("operateType", "1");
		return ConditionModel.builder()
				.code(getCode())
				.name(getMessageName())
				.optionType(OptionType.Simple)
				.dynamicModel(
						DynamicModel.<ConditionModel>builder()
							.url("smart/trigger/getCusFieldInfoList")
							.searchType(SearchType.Page)
							.code("id")
							.name("name")
							.params(groupSearch)
							.build())
				.build();
	}

	@Override
	public String getName() {
		return "自定义字段";
	}

	@Override
	public boolean match(TriggerWrapper<UserConnectP, UserConnectR> wrapper, Condition condition) {
		CrmCustomer customer=getCustomer(wrapper);
		if(customer==null) {
			return false;
		}
		String customerFields=customer.getCustomerFields();
		List<String> operatorValues=getOperatorList(condition);
		
		if(StringUtils.isNoneBlank(customerFields)) {
			List<Map<String,String>> list=JacksonUtil.toBean(customerFields, new TypeReference<List<Map<String,String>>>() {});
			String value=list.stream().filter(map->{
					return map.get("fieldId").equals(condition.getSubCondition());
				}).map(map->{
					return map.get("fieldValue");
				}).findAny()
				.orElse(null);
			if(StringUtils.isNoneBlank(value)) {
				//TODO 需要在这里加一个类型，如果是多选，只能是IN,或者 Not IN  EQ? NEQ,ISNULL,ISNOTNULL
				//List<String> values=Lists.newArrayList(value.split(","));
				return getCustomer(wrapper)!=null&&condition.getDecision().match(operatorValues, value,null);
			}
		}
		return false;
		
	}

}
